#!/bin/bash -x

# Qt4 based app

# Now we are inside CentOS 6
grep -r "CentOS release 6" /etc/redhat-release || exit 1

# Determine which architecture should be built
if [[ "$(/bin/arch)" = "i686" ||  "$(/bin/arch)" = "x86_64" ]] ; then
	ARCH=$(arch)
else
	echo "Architecture could not be determined"
	exit 1
fi

git_pull_rebase_helper()
{
	git reset --hard HEAD
        git pull
}

if [ -z "$NO_DOWNLOAD" ] ; then

# Not needed in this Recipe?
# Workaround for:
# cannot find -lstdc++_nonshared
# Force-install devtoolset-2-libstdc++-devel i686
# if [ ! -e /opt/rh/devtoolset-2/root/usr/lib/gcc/i686-redhat-linux ] ; then
#   cd /
#   wget http://people.centos.org/~tru/devtools-2/6/i386/RPMS/devtoolset-2-libstdc++-devel-4.8.2-15.el6.i686.rpm -O - | rpm2cpio | cpio -idm
#   cd -
# fi
# 
# Workaround for:
# checking for QT4... no
# configure: error: Qt4 not found
# We need at least Qt 4.8, hence we get it from kde.repo
# wget http://kdeforge.unl.edu/apt/kde-redhat/epel/kde.repo -O /etc/yum.repos.d/kde.repo
#
# Some packages (e.g. ffmpeg) are not in the official repository, but can be installed from the rpmfusion repository
# 
# yum localinstall -y --nogpgcheck http://download1.rpmfusion.org/free/el/updates/6/i386/rpmfusion-free-release-6-1.noarch.rpm http://download1.rpmfusion.org/nonfree/el/updates/6/i386/rpmfusion-nonfree-release-6-1.noarch.rpm

yum install qt-devel gcc-c++ libusb1-devel

if [ ! -d robocut ] ; then
  git clone https://github.com/nosliwneb/robocut.git
fi
cd robocut/
git_pull_rebase_helper

APP=Robocut

mkdir -p ./$APP.AppDir/usr/bin

qmake-qt4 
make
strip robocut

cd $APP.AppDir/

mv ../robocut ../images ./usr/bin/

wget -c "https://github.com/probonopd/AppImageKit/releases/download/5/AppRun" # (64-bit)
chmod a+x ./AppRun

# Move icons into place so that AppImageAssistant finds them
cp ./usr/bin/images/icon.png robocut.png

# TODO: Get appdata
# mkdir -p ./usr/metainfo/appdata/
# ...

# Get desktop file
cat > robocut.desktop <<\EOF
[Desktop Entry]
Icon=robocut
Exec=robocut
Name=Robocut
Categories=Graphics;
EOF

# Add desktop integration
XAPP=robocut
wget -O ./usr/bin/$XAPP.wrapper https://raw.githubusercontent.com/probonopd/AppImageKit/master/desktopintegration
chmod a+x ./usr/bin/$XAPP.wrapper
sed -i -e "s|Exec=$XAPP|Exec=$XAPP.wrapper|g" $XAPP.desktop

# Go out of AppImage
cd ..

# Figure out $VERSION
VERSION=$(grep -r VERSION Robocut.pro | cut -d " " -f 3 | sed -e 's|_||g')
echo $VERSION

wget -c "https://github.com/probonopd/AppImageKit/releases/download/5/AppImageAssistant" # (64-bit)
chmod a+x ./AppImageAssistant
mkdir -p ../out
rm ../out/$APP"-"$VERSION"-x86_64.AppImage" || true
./AppImageAssistant ./$APP.AppDir/ ../out/$APP"-"$VERSION"-x86_64.AppImage"

### When running on CentOS 6.7 x86_64
### ./AppImageAssistant: /lib64/libc.so.6: version `GLIBC_2.14' not found (required by ./AppImageAssistant)
### HOW TO SOLVE THIS? Why is this not the case for the others?
